import { useEffect, useState } from 'react';
import {
  DocumentUtils,
  getQueryParam,
  QueryParamKeys,
  Playground,
  CMEVENTS,
} from '@amcax/base';
import { PickerMgr, Renderer3D, RendererMgr, Snaper } from '@amcax/renderer';
import { wsApi } from '../server/wsApi';
import { Constants } from '../common/Constants';
import { handleCoreEvent } from '../common/events/CoreEvent';
import { docMgr } from '../manager/DocumentManager';
import { cmdMgr } from '../manager/CmdManager';
import { csEvent } from '../common/events/EventCenter';
import {
  application,
  coreEngine,
  ctx2,
  environmentManager,
  userEvents,
} from '../module';
import './Index.scss';

let readOnly = DocumentUtils.isReadOnly();

export default function Main() {
  const [showViewCube, setShowViewCube] = useState(false);
  const [showLoading, setShowLoading] = useState(true);
  const showConnectMessage = false;
  useEffect(() => {
    startApp();
    return () => {};
  }, []);

  const startApp = () => {
    application.start({
      init: async () => {
        console.log('startApp');

        const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
        const documentVersion = getQueryParam<string>(QueryParamKeys.VERSION);

        // 开启WebSocket，连接NextCore
        const engine = await coreEngine.start(documentId, documentVersion);
        ctx2.set(Constants.CORE_ENGINE, engine);

        // 打开文档
        await wsApi.openDocument(documentVersion, readOnly);

        // 添加事件监听
        engine.attach(handleCoreEvent);

        // 更新特征树
        await docMgr.updateDocumentObjects();
        await docMgr.updateDocumentMaterials();

        // 初始化渲染器和拾取器
        await initRenderer();

        // 渲染模型
        const modelDatas = await wsApi.getVisualData();
        console.log('modelDatas', modelDatas);
        RendererMgr.getRender<Renderer3D>('3d')
          .renderModels(modelDatas)
          .finally(() => {
            // ctx2.viewer.sceneSetup.fit2DView();
            setTimeout(() => {
              ctx2.viewer.sceneSetup.updateViewportSize();
            }, 1000);
          });

        csEvent().init();

        // 更新undo/redo数量
        cmdMgr.updateUndoSize();

        setShowLoading(false);
        setShowViewCube(true);
      },
      environments: async () => {
        console.log('设置环境！！！！！！！！！！！！！！！！！！！！');
        const { airfoilEnvironment } = await import('../environments/airfoil');
        return [airfoilEnvironment];
      },
      loaded: () => {
        environmentManager.switchTo('Airfoil');
        ctx2.viewer.sceneSetup.fit2DView();
        userEvents.emit(CMEVENTS.CAD_SCENE_LOADED);
      },
    });
  };

  const initRenderer = () => {
    // 初始化渲染器
    RendererMgr.initRenderer(ctx2, '3d', () => {
      ctx2.viewer.requestRender();
      ctx2.viewer.sceneSetup.updatePixelBuffer();
    });
    RendererMgr.initRenderer(ctx2, '2d', () => {
      ctx2.viewer.requestRender();
      ctx2.viewer.sceneSetup.updatePixelBuffer();
    });
    // 初始化Picker
    const requestRenderFunction = () => {
      ctx2.viewer.requestRender();
    };

    PickerMgr.initPicker(ctx2, '3d', requestRenderFunction);
    PickerMgr.initPicker(ctx2, '2d', requestRenderFunction);

    // 设置snaper
    Snaper.init(ctx2);
  };

  return (
    <Playground
      ctx2={ctx2}
      style={{
        position: 'relative',
      }}
      // showViewCube={showViewCube}
      showLoading={showLoading}
      showConnectMessage={showConnectMessage}
    />
  );
}
